/**
 * Copyright @ 2019 HoldTime Inner Mongolia Co. Ltd.
 */
package com.holdtime.jtt809dataservice.server.processor;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.edata.common.LatLngTransforUtil;
import com.holdtime.jtt809dataservice.business.api.CarInfoService;
import com.holdtime.jtt809dataservice.common.bean.CarInfoRegisterReqDTO;
import com.holdtime.jtt809dataservice.common.bean.CarInfoReqDTO;
import com.holdtime.jtt809dataservice.common.bean.CarRealLocationReqDTO;
import com.holdtime.jtt809dataservice.common.event.MessageReceiveEvent;
import com.holdtime.jtt809dataservice.common.process.ProtocolProcessor;
import com.holdtime.jtt809dataservice.server.socket.TcpClient;
import com.holdtime.jtt809dataservice.server.util.LinksManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 项目名称： jtt809gateway<br>
 * 功能描述： UpExgMsgProcessor概述：主链路车辆动态信息交换业务处理<br>
 * 创  建 人： guoai<br>
 * 创建日期： 2019年7月29日<br>
 * 修  改 人：  <br>
 * 修改时间：<br>
 * 修改内容：<br>
 * 版      本： 1.0.0
 */
@Component
public @Slf4j class UpExgMsgProcessor implements ProtocolProcessor {
    @Resource
    private ProtocolJT809 protocolJT809;
    @Resource
    private CarInfoService carInfoService;

    private static AtomicInteger msgNum = new AtomicInteger(0);
    @Value("${location-time-range}")
    private long locationTimeRange;

    private long startTime;

    @Override
    public int getMsgID() {
        return UpExgMsg.MSG_ID;
    }

    @Override
    public void process(MessageReceiveEvent event) {
        JTT809Packet<RawBody> source = event.getSource();
        UpExgMsg<RawBody> upExgMsg = new UpExgMsg<>();
        upExgMsg.setData(new RawBody());
        upExgMsg.from(source.getBody().getRaw());
        //        IoSession session = event.getSession();

        if (upExgMsg.getDataType() == UpExgMsgRegister.MSG_ID) {
            UpExgMsgRegister(upExgMsg);
        }

        if (upExgMsg.getDataType() == UpExgMsgRealLocation.MSG_ID) {
            updateMsgNum(event.getSource().getMsgGnsscenterid());
            UpExgMsgRealLocation(upExgMsg);
        }
        // TODO
    }

    /**
     * @param msgGnsscenterid
     */
    private void updateMsgNum(long msgGnsscenterid) {
        int i = msgNum.incrementAndGet();
        if (i == 1) {
            startTime = System.currentTimeMillis() / 1000;
        }
        if (i >= 1000) {
            msgNum.set(0);
            DownTotalRecvBackMsg backMsg = new DownTotalRecvBackMsg();
            backMsg.setDynamicInfoTotal(i);
            backMsg.setStartTime(startTime);
            backMsg.setEndTime(System.currentTimeMillis() / 1000);
            JTT809Packet<DownTotalRecvBackMsg> packet = protocolJT809.getPacket(backMsg, DownTotalRecvBackMsg.MSG_ID, msgGnsscenterid);
            TcpClient subLink = LinksManager.getSubLink(msgGnsscenterid);
            if (subLink != null) {
                subLink.send(packet);
            }
        }
    }

    /**
     * 实时上传车辆定位信息
     *
     * @param upExgMsg
     */
    private void UpExgMsgRealLocation(UpExgMsg<RawBody> upExgMsg) {
        UpExgMsgRealLocation location = new UpExgMsgRealLocation();
        location.from(upExgMsg.getData().getRaw());

        LocalDateTime now = LocalDateTime.now();
        CarRealLocationReqDTO carLoginReqDTO = new CarRealLocationReqDTO();
        carLoginReqDTO.setLon(LatLngTransforUtil.transforMillionDegree(location.getLon()) + "");
        carLoginReqDTO.setLat(LatLngTransforUtil.transforMillionDegree(location.getLat()) + "");
        if (carLoginReqDTO.getLat().equals("0.0") || carLoginReqDTO.getLon().equals("0.0")) {
            return;
        }
        carLoginReqDTO.setVehicleNo(upExgMsg.getVehicleNo());
        carLoginReqDTO.setVehicleColor(upExgMsg.getVehicleColor().val + "");
        try {
            carLoginReqDTO.setUploadTime(LocalDateTimeUtil.of(location.getDateTime()));
        } catch (Exception e) {
            carLoginReqDTO.setUploadTime(now);
        }
        carLoginReqDTO.setSps(location.getVec1());
        carLoginReqDTO.setDrs(location.getVec2());
        carLoginReqDTO.setMileage(location.getVec3());
        carLoginReqDTO.setDirection(location.getDirection());
        carLoginReqDTO.setAltitude(location.getAltitude());
        carLoginReqDTO.setState(location.getState());
        carLoginReqDTO.setAlarm(location.getAlarm());
        //mongoTemplate.save(gwLocationNew);
//        if (carLoginReqDTO.getUploadTime().getTime() > (System.currentTimeMillis() + locationTimeRange * 60 * 1000)) {
//            return;
//        }
        if (carLoginReqDTO.getUploadTime().isAfter(now)) {
            carLoginReqDTO.setUploadTime(now);
        }
        carInfoService.dealCarRealLocationReq(carLoginReqDTO);
    }

    /**
     * 上传车辆注册信息
     *
     * @param upExgMsg
     */
    private void UpExgMsgRegister(UpExgMsg<RawBody> upExgMsg) {
        UpExgMsgRegister register = new UpExgMsgRegister();
        register.from(upExgMsg.getData().getRaw());
        CarInfoReqDTO<CarInfoRegisterReqDTO> carInfoReqDTO = new CarInfoReqDTO<>();
        carInfoReqDTO.setVehicleNo(upExgMsg.getVehicleNo());
        carInfoReqDTO.setVehicleColor(upExgMsg.getVehicleColor().val);
        CarInfoRegisterReqDTO carInfoData = new CarInfoRegisterReqDTO();
        carInfoData.setPlatformId(register.getPlatformId());
        carInfoData.setProducerId(register.getProducerId());
        carInfoData.setTerminalModelType(register.getTerminalModelType());
        carInfoData.setTerminalId(register.getTerminalId());
        carInfoData.setTerminalSimcode(register.getTerminalSimcode());
        carInfoReqDTO.setCarInfoData(carInfoData);
        carInfoService.dealCarInfoRegisterReq(carInfoReqDTO);
    }

}
